package com.sangmo.fts.process.inventory.calculator;

import com.sangmo.boot.framework.common.utils.ApplicationUtils;
import com.sangmo.boot.framework.data.json.context.KeyValue;
import com.sangmo.boot.framework.data.json.load.Calculator;
import com.sangmo.fts.basic.model.Goods;
import com.sangmo.fts.basic.service.GoodsService;
import com.sangmo.fts.process.inventory.model.IfLoan;
import com.sangmo.fts.process.inventory.model.IfWaybillItem;
import com.sangmo.fts.process.inventory.repo.IfWaybillItemRepo;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Component
public class IfLoanGoodsTotalAmountCalculator implements Calculator<IfLoan>, IfLoan.IIfLoanGoodsTotalAmountCalculator {
    @Override
    public Object calc(IfLoan bean, Collection<KeyValue> exts) {
        IfWaybillItemRepo ifWaybillItemRepo = ApplicationUtils.getBean(IfWaybillItemRepo.class);
        List<IfWaybillItem> waybillItems = ifWaybillItemRepo.findByWaybillId(bean.getWaybillId());
        GoodsService goodsService = ApplicationUtils.getBean(GoodsService.class);
        BigDecimal goodsTotalAmount = BigDecimal.ZERO;
        Map<Long, Goods> goodsMap = goodsService.getAllGoodsMapCache();
        for (IfWaybillItem item: waybillItems) {
            Goods goods = goodsMap.get(item.getGoodsId());
            BigDecimal price = (goods == null?BigDecimal.ZERO :goods.getPrice());
            goodsTotalAmount = goodsTotalAmount.add(price.multiply(item.getQuantity()));
        }
        return goodsTotalAmount;
    }
}
